package com.thread.sychronized;

/**
 * @author wangyingjie
 * @date
 * @remark Synchronized只要锁的是同一对象(或者类)，不同代码处也有用
 */
public class SynchronizedDemo implements Runnable{
    //不同代码处，都锁obj对象
    static Object obj = new Object();
    static volatile Integer i;

    public SynchronizedDemo(int count) {
        i = count;
    }

    @Override
    public void run() {
        if (i==2){
            i++;
            System.out.println("进111堵塞");
            synchronized (obj){
                System.out.println("活得锁Syn--1");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else {
            i++;
            System.out.println("进222堵塞");
            synchronized (obj){
                System.out.println("获得锁Syn--2");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread syn1 = new Thread(new SynchronizedDemo(0));
        Thread syn2 = new Thread(new SynchronizedDemo(1));
        syn1.start();
        Thread.sleep(1000);
        syn2.start();

    }
}
